﻿/*---------------------------------------------------------------------------------
-----------------***DaLianQianYi***-----------------------
-----------------作者：大连仟亿科技------------------------------------------------------
-----------------联系作者：www.qianyikeji.com----------------------------------
-----------------时间：2024/7/26 11:30:36------------------------------------------
----------------------------------------------------------------------------------*/


using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Donal.Xms.Common;

namespace Donal.Xms.Web.qianyi.common
{
    public partial class products_goods_edit : Web.UI.ManagePage
    {
        private string action = ""; //操作类型
        private int id = 0;
        private int category = 0;
        private int product = 0;
        private int status = 0;                

        protected void Page_Load(object sender, EventArgs e)
        {
            this.action = DTRequest.GetQueryString("action");
            this.id = DTRequest.GetQueryInt("id");
            this.category = DTRequest.GetQueryInt("category");
            this.product = DTRequest.GetQueryInt("product");
            this.status = DTRequest.GetQueryInt("status");

            if (hidPid.Value != "0")
            {
                CreateOtherField(Utils.ObjToInt(hidPid.Value));
            }
            hidPid.Value = product.ToString();

            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(action) && action == DTEnums.ActionEnum.Edit.ToString())
                {
                    if (this.id == 0)
                    {
                        JscriptMsg("传输参数不正确！", "back");
                        return;
                    }
                    if (!new BLL.products_goods().Exists(this.id))
                    {
                        JscriptMsg("产品规格不存在或已被删除！", "back");
                        return;
                    }
                }

                ChkAdminLevel("products_goods", DTEnums.ActionEnum.View.ToString()); //检查权限
                TreeBind();
                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    ShowInfo(this.id);
                }
                else
                {
                    CreateOtherField(product);
                }
            }
        }

        #region 扩展字段赋值=============================
        private List<Model.products_goods_filed> SetFieldValues(int _products_id)
        {
            DataTable dt = new BLL.products_attribute_field().GetList(_products_id, "").Tables[0];
            List<Model.products_goods_filed> dic = new List<Model.products_goods_filed>();

            foreach (DataRow dr in dt.Rows)
            {
                //查找相应的控件
                switch (dr["control_type"].ToString())
                {
                    case "single-text": //单行文本
                        TextBox txtControl = FindControl("field_control_" + dr["name"].ToString()) as TextBox;
                        if (txtControl != null)
                        {
                            dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = txtControl.Text.Trim() });
                        }
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        HtmlTextArea htmlTextAreaControl = FindControl("field_control_" + dr["name"].ToString()) as HtmlTextArea;
                        if (htmlTextAreaControl != null)
                        {
                            dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = htmlTextAreaControl.Value });
                        }
                        break;
                    case "images": //图片上传
                        goto case "single-text";
                    case "video": //视频上传
                        goto case "single-text";
                    case "number": //数字
                        goto case "single-text";
                    case "datetime": //时间日期
                        goto case "single-text";
                    case "checkbox": //复选框
                        CheckBox cbControl = FindControl("field_control_" + dr["name"].ToString()) as CheckBox;
                        if (cbControl != null)
                        {
                            if (cbControl.Checked == true)
                            {
                                dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = "1" });
                            }
                            else
                            {
                                dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = "0" });
                            }
                        }
                        break;
                    case "multi-radio": //多项单选
                        RadioButtonList rblControl = FindControl("field_control_" + dr["name"].ToString()) as RadioButtonList;
                        if (rblControl != null)
                        {
                            dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = rblControl.SelectedValue });
                        }
                        break;
                    case "multi-checkbox": //多项多选
                        CheckBoxList cblControl = FindControl("field_control_" + dr["name"].ToString()) as CheckBoxList;
                        if (cblControl != null)
                        {
                            StringBuilder tempStr = new StringBuilder();
                            for (int i = 0; i < cblControl.Items.Count; i++)
                            {
                                if (cblControl.Items[i].Selected)
                                {
                                    tempStr.Append(cblControl.Items[i].Value.Replace(',', '，') + ",");
                                }
                            }
                            dic.Add(new Model.products_goods_filed() { field_title = dr["title"].ToString(), field_name = dr["name"].ToString(), field_value = Utils.DelLastComma(tempStr.ToString()) });
                        }
                        break;
                }
            }
            return dic;
        }
        #endregion

        #region 创建其它扩展字段=========================
        private void CreateOtherField(int _products_id)
        {
            List<Model.products_attribute_field> ls = new BLL.products_attribute_field().GetModelList(_products_id);
            if (ls.Count > 0)
            {
                field_tab_content.Visible = true;
            }
            foreach (Model.products_attribute_field modelt in ls)
            {
                //创建一个dl标签
                HtmlGenericControl htmlDL = new HtmlGenericControl("dl");
                HtmlGenericControl htmlDT = new HtmlGenericControl("dt");
                HtmlGenericControl htmlDD = new HtmlGenericControl("dd");
                htmlDT.InnerHtml = modelt.title;

                switch (modelt.control_type)
                {
                    case "single-text": //单行文本
                        //创建一个TextBox控件
                        TextBox txtControl = new TextBox();
                        txtControl.ID = "field_control_" + modelt.name;
                        //CSS样式及TextMode设置
                        if (modelt.control_type == "single-text") //单行
                        {
                            txtControl.CssClass = "input normal";
                            //是否密码框
                            if (modelt.is_password == 1)
                            {
                                txtControl.TextMode = TextBoxMode.Password;
                            }
                        }
                        else if (modelt.control_type == "multi-text") //多行
                        {
                            txtControl.CssClass = "input";
                            txtControl.TextMode = TextBoxMode.MultiLine;
                        }
                        else if (modelt.control_type == "number") //数字
                        {
                            txtControl.CssClass = "input small";
                        }
                        else if (modelt.control_type == "datetime") //时间日期
                        {
                            txtControl.CssClass = "input rule-date-input";
                            txtControl.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})");
                        }
                        else if (modelt.control_type == "images" || modelt.control_type == "video") //图片视频
                        {
                            txtControl.CssClass = "input normal upload-path";
                        }
                        //设置默认值
                        txtControl.Text = modelt.default_value;
                        //验证提示信息
                        if (!string.IsNullOrEmpty(modelt.valid_tip_msg))
                        {
                            txtControl.Attributes.Add("tipmsg", modelt.valid_tip_msg);
                        }
                        //验证失败提示信息
                        if (!string.IsNullOrEmpty(modelt.valid_error_msg))
                        {
                            txtControl.Attributes.Add("errormsg", modelt.valid_error_msg);
                        }
                        //验证表达式
                        if (!string.IsNullOrEmpty(modelt.valid_pattern))
                        {
                            txtControl.Attributes.Add("datatype", modelt.valid_pattern);
                            txtControl.Attributes.Add("sucmsg", " ");
                        }
                        //创建一个Label控件
                        Label labelControl = new Label();
                        labelControl.CssClass = "Validform_checktip";
                        labelControl.Text = modelt.valid_tip_msg;

                        //将控件添加至DD中
                        htmlDD.Controls.Add(txtControl);
                        //如果是图片则添加上传按钮
                        if (modelt.control_type == "images")
                        {
                            HtmlGenericControl htmlBtn = new HtmlGenericControl("div");
                            htmlBtn.Attributes.Add("class", "upload-box upload-img");
                            htmlBtn.Attributes.Add("style", "margin-left:4px;");
                            htmlDD.Controls.Add(htmlBtn);
                        }
                        //如果是视频则添加上传按钮
                        if (modelt.control_type == "video")
                        {
                            HtmlGenericControl htmlBtn = new HtmlGenericControl("div");
                            htmlBtn.Attributes.Add("class", "upload-box upload-video");
                            htmlBtn.Attributes.Add("style", "margin-left:4px;");
                            htmlDD.Controls.Add(htmlBtn);
                        }
                        htmlDD.Controls.Add(labelControl);
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        HtmlTextArea txtTextArea = new HtmlTextArea();
                        txtTextArea.ID = "field_control_" + modelt.name;
                        //txtTextArea.Attributes.Add("style", "visibility:hidden;");
                        //是否简洁型编辑器
                        if (modelt.editor_type == 1)
                        {
                            txtTextArea.Attributes.Add("class", "editor-mini");
                        }
                        else
                        {
                            txtTextArea.Attributes.Add("class", "editor");
                        }
                        txtTextArea.Value = modelt.default_value; //默认值
                        //验证提示信息
                        if (!string.IsNullOrEmpty(modelt.valid_tip_msg))
                        {
                            txtTextArea.Attributes.Add("tipmsg", modelt.valid_tip_msg);
                        }
                        //验证失败提示信息
                        if (!string.IsNullOrEmpty(modelt.valid_error_msg))
                        {
                            txtTextArea.Attributes.Add("errormsg", modelt.valid_error_msg);
                        }
                        //验证表达式
                        if (!string.IsNullOrEmpty(modelt.valid_pattern))
                        {
                            txtTextArea.Attributes.Add("datatype", modelt.valid_pattern);
                            txtTextArea.Attributes.Add("sucmsg", " ");
                        }
                        //创建一个Label控件
                        Label labelControl2 = new Label();
                        labelControl2.CssClass = "Validform_checktip";
                        labelControl2.Text = modelt.valid_tip_msg;
                        //将控件添加至DD中
                        htmlDD.Controls.Add(txtTextArea);
                        htmlDD.Controls.Add(labelControl2);
                        break;
                    case "images": //图片上传
                        goto case "single-text";
                    case "video": //视频上传
                        goto case "single-text";
                    case "number": //数字
                        goto case "single-text";
                    case "datetime": //时间日期
                        goto case "single-text";
                    case "checkbox": //复选框
                        CheckBox cbControl = new CheckBox();
                        cbControl.ID = "field_control_" + modelt.name;
                        //默认值
                        if (modelt.default_value == "1")
                        {
                            cbControl.Checked = true;
                        }
                        HtmlGenericControl htmlDiv1 = new HtmlGenericControl("div");
                        htmlDiv1.Attributes.Add("class", "rule-single-checkbox");
                        htmlDiv1.Controls.Add(cbControl);
                        //将控件添加至DD中
                        htmlDD.Controls.Add(htmlDiv1);
                        if (!string.IsNullOrEmpty(modelt.valid_tip_msg))
                        {
                            //创建一个Label控件
                            Label labelControl3 = new Label();
                            labelControl3.CssClass = "Validform_checktip";
                            labelControl3.Text = modelt.valid_tip_msg;
                            htmlDD.Controls.Add(labelControl3);
                        }
                        break;
                    case "multi-radio": //多项单选
                        RadioButtonList rblControl = new RadioButtonList();
                        rblControl.ID = "field_control_" + modelt.name;
                        rblControl.RepeatDirection = RepeatDirection.Horizontal;
                        rblControl.RepeatLayout = RepeatLayout.Flow;
                        HtmlGenericControl htmlDiv2 = new HtmlGenericControl("div");
                        htmlDiv2.Attributes.Add("class", "rule-multi-radio");
                        htmlDiv2.Controls.Add(rblControl);
                        //赋值选项
                        string[] valArr = modelt.item_option.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                        for (int i = 0; i < valArr.Length; i++)
                        {
                            string[] valItemArr = valArr[i].Split('|');
                            if (valItemArr.Length == 2)
                            {
                                rblControl.Items.Add(new ListItem(valItemArr[0], valItemArr[1]));
                            }
                        }
                        rblControl.SelectedValue = modelt.default_value; //默认值
                        //创建一个Label控件
                        Label labelControl4 = new Label();
                        labelControl4.CssClass = "Validform_checktip";
                        labelControl4.Text = modelt.valid_tip_msg;
                        //将控件添加至DD中
                        htmlDD.Controls.Add(htmlDiv2);
                        htmlDD.Controls.Add(labelControl4);
                        break;
                    case "multi-checkbox": //多项多选
                        CheckBoxList cblControl = new CheckBoxList();
                        cblControl.ID = "field_control_" + modelt.name;
                        cblControl.RepeatDirection = RepeatDirection.Horizontal;
                        cblControl.RepeatLayout = RepeatLayout.Flow;
                        HtmlGenericControl htmlDiv3 = new HtmlGenericControl("div");
                        htmlDiv3.Attributes.Add("class", "rule-multi-checkbox");
                        htmlDiv3.Controls.Add(cblControl);
                        //赋值选项
                        string[] valArr2 = modelt.item_option.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                        for (int i = 0; i < valArr2.Length; i++)
                        {
                            string[] valItemArr2 = valArr2[i].Split('|');
                            if (valItemArr2.Length == 2)
                            {
                                cblControl.Items.Add(new ListItem(valItemArr2[0], valItemArr2[1]));
                            }
                        }
                        cblControl.SelectedValue = modelt.default_value; //默认值
                        //创建一个Label控件
                        Label labelControl5 = new Label();
                        labelControl5.CssClass = "Validform_checktip";
                        labelControl5.Text = modelt.valid_tip_msg;
                        //将控件添加至DD中
                        htmlDD.Controls.Add(htmlDiv3);
                        htmlDD.Controls.Add(labelControl5);
                        break;
                }

                //将DT和DD添加到DL中
                htmlDL.Controls.Add(htmlDT);
                htmlDL.Controls.Add(htmlDD);
                //将DL添加至field_tab_content中
                field_tab_content.Controls.Add(htmlDL);
            }
        }
        #endregion

        #region 绑定类别=================================
        private void TreeBind()
        {
            BLL.products_category bll = new BLL.products_category();
            DataTable dt = bll.GetList(0);

            this.ddlCategoryId.Items.Clear();
            this.ddlCategoryId.Items.Add(new ListItem("请选择类别...", ""));

            this.ddlProducts.Items.Clear();
            this.ddlProducts.Items.Add(new ListItem("所有规格", ""));

            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["id"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["title"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlCategoryId.Items.Add(new ListItem(Title, Id));
                }
            }

            if (category > 0)
            {
                ddlCategoryId.SelectedValue = category.ToString();
                ProductsBind();
            }

        }
        #endregion

        #region 绑定规格=================================
        private void ProductsBind()
        {
            if (category > 0)
            {
                BLL.products bll = new BLL.products();
                DataSet dt = bll.GetList(0, " category_id in(select id from dt_products_category where class_list like '%," + category + ",%')", "sort_id");

                if (Utils.CheckDataSet(dt))
                {
                    foreach (DataRow dr in dt.Tables[0].Rows)
                    {
                        string Id = dr["id"].ToString();
                        string Title = dr["title"].ToString().Trim();
                        this.ddlProducts.Items.Add(new ListItem(Title, Id));
                    }
                }

                ddlProducts.SelectedValue = product.ToString();
            }
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.products_goods bll = new BLL.products_goods();
            Model.products_goods model = bll.GetModel(_id);

            txtTitle.Text = model.title;
            txtSub_title.Text = model.sub_title;

            if (category == 0)
            {
                category = Utils.ObjToInt(new BLL.products().GetValue(model.products_id, "category_id"));
                TreeBind();
            }

            if (product == 0)
            {
                CreateOtherField(model.products_id);
                product = model.products_id;
            }
            else
            {
                CreateOtherField(product);
            }

            hidPid.Value = product.ToString();
            ddlProducts.SelectedValue = product.ToString();

            txtCallIndex.Text = model.call_index;
            txtLinkUrl.Text = model.link_url;
            txtImgUrl.Text = model.img_url;

            if (status > 0)
            {
                cbStatus.Checked = status == 1 ? true : false;
            }
            else
            {
                cbStatus.Checked = model.status == 0;
            }

            txtSortId.Text = model.sort_id.ToString();
            txtProduct_code.Text = model.erp_goods_no;
            txtSell_price.Text = model.sell_price.ToString();
            txtContent.Value = model.contents;
            txtAbstracts.Text = model.abstracts;
            txtAddTime.Text = Utils.ObjectToDateTime(model.add_time, DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss");

            //扩展字段赋值
            List<Model.products_attribute_field> ls1 = new BLL.products_attribute_field().GetModelList(product);
            foreach (Model.products_attribute_field modelt1 in ls1)
            {
                switch (modelt1.control_type)
                {
                    case "single-text": //单行文本
                        TextBox txtControl = FindControl("field_control_" + modelt1.name) as TextBox;
                        if (txtControl != null && model.fields.Exists(x => x.field_name == modelt1.name))
                        {
                            if (modelt1.is_password == 1)
                            {
                                txtControl.Attributes.Add("value", model.fields.Find(x => x.field_name == modelt1.name).field_value);
                            }
                            else
                            {
                                txtControl.Text = model.fields.Find(x => x.field_name == modelt1.name).field_value;
                            }
                        }
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        HtmlTextArea txtAreaControl = FindControl("field_control_" + modelt1.name) as HtmlTextArea;
                        if (txtAreaControl != null && model.fields.Exists(x => x.field_name == modelt1.name))
                        {
                            txtAreaControl.Value = model.fields.Find(x => x.field_name == modelt1.name).field_value;
                        }
                        break;
                    case "images": //图片上传
                        goto case "single-text";
                    case "video": //视频上传
                        goto case "single-text";
                    case "number": //数字
                        goto case "single-text";
                    case "datetime": //时间日期
                        goto case "single-text";
                    case "checkbox": //复选框
                        CheckBox cbControl = FindControl("field_control_" + modelt1.name) as CheckBox;
                        if (cbControl != null && model.fields.Exists(x => x.field_name == modelt1.name))
                        {
                            if (model.fields.Find(x => x.field_name == modelt1.name).field_value == "1")
                            {
                                cbControl.Checked = true;
                            }
                            else
                            {
                                cbControl.Checked = false;
                            }
                        }
                        break;
                    case "multi-radio": //多项单选
                        RadioButtonList rblControl = FindControl("field_control_" + modelt1.name) as RadioButtonList;
                        if (rblControl != null && model.fields.Exists(x => x.field_name == modelt1.name))
                        {
                            rblControl.SelectedValue = model.fields.Find(x => x.field_name == modelt1.name).field_value;
                        }
                        break;
                    case "multi-checkbox": //多项多选
                        CheckBoxList cblControl = FindControl("field_control_" + modelt1.name) as CheckBoxList;
                        if (cblControl != null && model.fields.Exists(x => x.field_name == modelt1.name))
                        {
                            string[] valArr = model.fields.Find(x => x.field_name == modelt1.name).field_value.Split(',');
                            for (int i = 0; i < cblControl.Items.Count; i++)
                            {
                                cblControl.Items[i].Selected = false; //先取消默认的选中
                                foreach (string str in valArr)
                                {
                                    if (cblControl.Items[i].Value == str)
                                    {
                                        cblControl.Items[i].Selected = true;
                                    }
                                }
                            }
                        }
                        break;
                }
            }


        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            Model.products_goods model = new Model.products_goods();
            BLL.products_goods bll = new BLL.products_goods();

            model.title = txtTitle.Text;
            model.products_id = int.Parse(ddlProducts.SelectedValue);
            model.call_index = txtCallIndex.Text;
            model.link_url = txtLinkUrl.Text;
            model.img_url = txtImgUrl.Text;

            model.sub_title = txtSub_title.Text;
            model.status = cbStatus.Checked ? 0 : 1;
            model.sort_id = int.Parse(txtSortId.Text);

            model.erp_goods_no = txtProduct_code.Text;
            model.sell_price = decimal.Parse(txtSell_price.Text);

            model.contents = txtContent.Value;
            model.abstracts = txtAbstracts.Text;
            model.add_time = DateTime.Now;

            model.fields = SetFieldValues(model.products_id); //扩展字段赋值

            if (bll.Add(model) > 0)
            {
                AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加规格规格成功！"); //规格日志
                return true;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = false;
            BLL.products_goods bll = new BLL.products_goods();
            Model.products_goods model = bll.GetModel(_id);

            model.title = txtTitle.Text;
            model.products_id = int.Parse(ddlProducts.SelectedValue);
            model.call_index = txtCallIndex.Text;
            model.link_url = txtLinkUrl.Text;
            model.img_url = txtImgUrl.Text;

            model.sub_title = txtSub_title.Text;
            model.status = cbStatus.Checked ? 0 : 1;
            model.sort_id = int.Parse(txtSortId.Text);
            model.erp_goods_no = txtProduct_code.Text;
            model.sell_price = decimal.Parse(txtSell_price.Text);

            model.contents = txtContent.Value;
            model.abstracts = txtAbstracts.Text;

            model.fields = SetFieldValues(model.products_id); //扩展字段赋值

            if (bll.Update(model))
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改规格成功！"); //规格日志
                result = true;
            }

            return result;
        }
        #endregion

        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("products_goods", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", string.Empty);
                    return;
                }
                JscriptMsg("修改规格成功！", "products_goods_list.aspx");
            }
            else //添加
            {
                ChkAdminLevel("products_goods", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", string.Empty);
                    return;
                }
                JscriptMsg("添加规格成功！", "products_goods_list.aspx");
            }
        }

        protected void ddlCategoryId_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlProducts.SelectedIndex = 0;
            Redirect();
        }

        protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            Redirect();
        }

        private void Redirect()
        {
            Response.Redirect(Utils.CombUrlTxt("products_goods_edit.aspx", "action={0}&category={1}&status={2}&product={3}&id={4}",
                    action, ddlCategoryId.SelectedValue, (cbStatus.Checked ? "1" : "2"), ddlProducts.SelectedValue, id.ToString()));
        }
    }
}

